#!/usr/bin/env python
# -*- coding: utf-8 -*-
import dojango.forms as df
from django.core.urlresolvers import reverse
from django.utils.safestring import mark_safe
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned

from host_install.models import InstallationOrder, INSTALL_STATUS
from common.forms import ModelFormTableMixin, MyDojoFilteringSelect

import random
import string


class InstallationOrderForm(df.ModelForm):
    class Meta:
        model = InstallationOrder
        fields = ("type", "serial", "hostname", "site", "fai_classes", "ip",
                  "netmask", "gateway", "dns1", "dns2", "ip_mca", "ip_clarilab",
                  "supplier", "inventory", "location", "commentaire",)
                #"rootpw",
        widgets = {'site': MyDojoFilteringSelect(),
                 'supplier': MyDojoFilteringSelect(),
                 'type': MyDojoFilteringSelect(),
                 'ip': df.IPAddressTextInput(),
                 'gateway': df.IPAddressTextInput(),
                 'dns1': df.IPAddressTextInput(),
                 'dns2': df.IPAddressTextInput(),
                 'ip_mca': df.IPAddressTextInput(),
                 'ip_clarilab': df.IPAddressTextInput(),
                 'netmask': df.IPAddressTextInput(),
                 'commentaire': df.Textarea({"rows": 999, "cols": 999}),
                }

    def __init__(self, *args, **kwargs):
        super(df.ModelForm, InstallationOrderForm).__init__(self, *args, **kwargs)
        if(not self.instance.pk):
            avail_chars = [c for c in string.letters + string.digits
                          if c not in ('I', 'l', '1', 'O', '0')]
            self.instance.rootpw = ''.join(random.choice(avail_chars)
                                           for i in range(10))
            self.install_secret = ''.join(random.choice(avail_chars)
                                          for i in range(30))
            self.instance.status = 1

    def clean(self):
        cd = self.cleaned_data
        if not cd.get("serial", True):
            cd["serial"] = None
        elif cd.get("serial", False):
            cd["serial"] = cd["serial"].lower()
            if self.instance.id is None:
                try:
                    existing = InstallationOrder.objects.filter(serial=cd["serial"]).get()
                except(ObjectDoesNotExist, MultipleObjectsReturned):
                    pass
                else:
                    raise df.ValidationError(mark_safe(
                            "Ce numéro de série est déjà utilisé <a href='" +
                             reverse("host_install.modify", args=(existing.id,)) +
                            "'>vous povez modifier cet ordre</a>"))
        return cd


class SearchOrderForm(df.Form, ModelFormTableMixin):
    status = df.ChoiceField(choices=[(0, "")] + [(i, s) for i, s, c in INSTALL_STATUS],
                            widget=MyDojoFilteringSelect, required=False)

    def search(self, qs):
        cd = self.cleaned_data
        if cd['status'] != "0":
            qs = qs.filter(status__in=cd['status'])
        return qs

# vim:set et sts=4 ts=4 tw=80:
